/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rom.factory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import rom.mob.Mob;

/**
 *
 * @author Luis
 */
public class MobFactory {
    
    private ArrayList<Mob> mobs = new ArrayList<>();
    
    public void addMob(Mob mob) {
        if (isValid(mob)) {
            mobs.add(mob);
        }
    }

    public void removeMob(Mob mob) {
        if (mobs.contains(mob)) {
            mobs.remove(mob);
        }
    }

    public Mob getIMob(int id) {
        for (Mob m : mobs) {
            if (m.getId() == id) {
                return m;
            }
        }
        return null;
    }

    public Mob getMob(String name) {
        for (Mob m : mobs) {
            if (m.geteName().equals(name)) {
                return m;
            }
        }
        return null;
    }

    public Boolean isValid(Mob mob) {
        for (Mob m : mobs) {
            if (m.getId() == mob.getId()) {
                return false;
            }
        }
        return true;
    }

    public int size() {
        return mobs.size();
    }

    public void saveMob(Mob mob, File file) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(mob);
            oos.flush();
        }
    }

    public Mob readMob(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            Object aux = ois.readObject();

            while (aux != null) {
                if (aux instanceof Mob) {
                    return (Mob) aux;
                }
            }
        }
        return null;
    }    
}
